//
//  HJJSONRequestSerializer.m
//  KaiChat
//
//  Created by lx on 2023/12/5.
//

#import "HJJSONRequestSerializer.h"
#import "HJCryptoTool.h"

@implementation HJJSONRequestSerializer


#pragma mark - AFURLRequestSerialization

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(id)parameters
                                        error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(request);
        
    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
        return [super requestBySerializingRequest:request withParameters:parameters error:error];
    }
    
    NSMutableURLRequest *mutableRequest = [request mutableCopy];
    
    [self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
        if (![request valueForHTTPHeaderField:field]) {
            [mutableRequest setValue:value forHTTPHeaderField:field];
        }
    }];


    if (parameters) {
        if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
            [mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        }
        
        HJAppEnvType appEnvType = getAppEnvType();
        BOOL isCrypto = isUseCrypto() || ((appEnvType == HJAppEnvTypePro || appEnvType == HJAppEnvTypePre) && [request.URL.path containsString:@"wallet"]);
        if ([[[request HTTPMethod] uppercaseString] isEqualToString:@"POST"] && [request.URL.absoluteString hasPrefix:getBaseUrlString()] && isCrypto) {
            TJLog(@"开始加密");
            NSString *json = [parameters mj_JSONString];
            NSString *iv = nil;
            NSString *encryptString = [HJCryptoTool encryptString:json iv:&iv];
            [mutableRequest setValue:iv forHTTPHeaderField:@"Key"];
            NSData *jsonData = [encryptString dataUsingEncoding:NSUTF8StringEncoding];
            [mutableRequest setHTTPBody:jsonData];
            return mutableRequest;
        }
        
        if (![NSJSONSerialization isValidJSONObject:parameters]) {
            if (error) {
                NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
                *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
            }
            return nil;
        }
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
        if (!jsonData) {
            return nil;
        }
        [mutableRequest setHTTPBody:jsonData];
    }
    
    return mutableRequest;
}



@end
